package com.sora.sora.server.service.impl;

import com.sora.sora.common.constant.FilePath;
import com.sora.sora.common.exception.ApiException;
import com.sora.sora.common.model.entity.UserEntity;
import com.sora.sora.message.service.MailService;
import com.sora.sora.server.mapper.UserMapper;
import com.sora.sora.server.model.bo.UserBasicConvert;
import com.sora.sora.server.model.vo.UserVO;
import com.sora.sora.server.service.UserService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    MailService mailService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private PasswordEncoder passwordEncoder;


    @Override
    public UserVO showUser(int uid) {
        UserEntity entity = userMapper.queryUserById(uid);
        if (entity == null) {
            return null;
        }
        UserVO userVO = UserBasicConvert.INSTANCE.entityToVO(entity);
        return userVO;
    }

    @Override
    public String uploadAvatar(int uid, MultipartFile file) {
        String originName = file.getOriginalFilename();
//        String suffix = originName.substring(originName.lastIndexOf("."));
//        String fileName = System.currentTimeMillis() + originName;
        String path = FilePath.AVATAR_PATH;
//        String saveUrl = path + "\\" + uid + "\\" + fileName;
        String saveUrl = path + "\\" + uid + "\\" + "avatar.jpg";

        File file1;
        try {
            file1 = new File(saveUrl);
            file1.mkdirs();
            file.transferTo(file1);
        } catch (IOException e) {
            throw new ApiException("上传失败");
        }

        if (userMapper.uploadAvatar(saveUrl, uid) <= 0) {
            file1.delete();
            return null;
        }
        return saveUrl;
    }

    @Override
    public boolean updatePassword(int uid, String password) {
        int i = userMapper.updatePassword(uid, passwordEncoder.encode(password));
        if (i > 0) {
            mailService.infoPasswordChange(uid);
            return true;
        }
        return false;
    }

    @Override
    public boolean updateEmail(int uid, String email) {
        String oldEmail = userMapper.queryEmailById(uid);
        int i = userMapper.updateEmail(uid, email);
        if (i > 0) {
            mailService.infoEmailChange(uid, oldEmail);
            return true;
        }
        return false;
    }

    @Override
    public boolean updaateSignature(int uid, String sign) {
        return userMapper.updateSign(uid, sign) > 0;
    }
}
